﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevComponents.DotNetBar.Controls;
using System.Windows.Forms;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing;
using KP_CommonLibrary.KP_CommonControls;


namespace TestMaskInput
{
    public class InputSoBn : MaskedTextBoxAdv, ISupportInitialize
    {
        public InputSoBn()
            : base()
        {
            base.Size = new Size(80, 25);
            base.Font = KP_UIConfig.EditControlFont;
        }
        private string _PrefixPattern = "9999", _MiddlePattern = "DK-HKD", _SuffixPattern = "9999";
        [DefaultValue("9999")]
        public string PrefixPattern
        {
            get
            {
                return _PrefixPattern;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                    value = "9999";
                string oldSuffix = "";
                string oldPrefix = "";
                if (!isInit)
                {
                    oldSuffix = SuffixValueString;
                    oldPrefix = PrefixValueString;
                }
                _PrefixPattern = value;
                if (!isInit)
                {
                    PatternChange(oldPrefix, oldSuffix);
                }
            }

        }
        [DefaultValue("DK-HKD")]
        public string MiddlePattern
        {
            get
            {
                return _MiddlePattern;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                    value = "DK-HKD";
                string oldSuffix = "";
                string oldPrefix = "";
                if (!isInit)
                {
                    oldSuffix = SuffixValueString;
                    oldPrefix = PrefixValueString;
                }
                _MiddlePattern = value;
                if (!isInit)
                {
                    PatternChange(oldPrefix, oldSuffix);
                }

            }
        }
        [DefaultValue("9999")]
        public string SuffixPattern
        {
            get
            {
                return _SuffixPattern;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                    value = "9999";
                string oldSuffix = "";
                string oldPrefix = "";
                if (!isInit)
                {
                    oldPrefix = PrefixValueString;
                    oldSuffix = SuffixValueString;
                }
                _SuffixPattern = value;

                if (!isInit)
                {
                    PatternChange(oldPrefix, oldSuffix);
                }
            }
        }

        void PatternChange(string oldPrefix, string oldSuffix)
        {

            Mask = PrefixPattern + "/" + MiddlePattern + "/" + SuffixPattern;
            Text = oldPrefix + "/" + MiddlePattern + "/" + oldSuffix;
        }

        public string SoBienNhan
        {
            get
            {
                return Text;
            }
            set
            {
                if (!isInit)
                    value = value.PadLeft(Mask.Length, ' ');
                base.Text = value;
            }
        }

        int WM_KEYDOWN = 0x100;
        int WM_CHAR = 0x102;

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {


            if (msg.Msg == WM_KEYDOWN)
            {
                int pos = SelectionStart;
                int lenght = SelectionLength;
                Keys k = keyData;

                if (Convert.ToBoolean((Control.ModifierKeys & Keys.Modifiers)))
                {

                    return base.ProcessCmdKey(ref msg, keyData);

                }
                if (lenght == Text.Length)
                {

                    Text = "";
                    pos = 0;
                    lenght = 0;
                    SelectionStart = 0;
                    SelectionLength = 0;
                }

                if (pos <= PrefixPattern.Length)
                    if (ProcessKeyAtPrefix(pos, lenght, k))
                        return true;
                if (pos >= PrefixPattern.Length)
                    if (ProcessKeyAtSuffix(pos, lenght, k))
                        return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        bool ProcessKeyAtPrefix(int position, int selectionLenght, Keys k)
        {
            try
            {
                string prefixValue, prePos, sufPos;

                if (k == Keys.Tab
                    || k == Keys.Enter
                    || (k == Keys.Right && (position == PrefixPattern.Length)))
                {
                    SelectionStart = PrefixPattern.Length + MiddlePattern.Length + 2;
                    SelectionLength = 0;
                    return true;
                }

                prefixValue = Text.Substring(0, PrefixPattern.Length);
                if (prefixValue.IndexOf("_") >= 0)
                    prefixValue = prefixValue.Replace('_', ' ');
                prePos = prefixValue.Substring(0, position).Trim();


                if (position < PrefixPattern.Length)
                    sufPos = prefixValue.Substring(position + selectionLenght, PrefixPattern.Length - selectionLenght - position).Trim();
                else sufPos = "";

                bool eatKey = ProcessKey(ref prePos, ref sufPos, k, true, position, selectionLenght);
                if (eatKey)
                {
                    prefixValue = prePos + sufPos;
                    prefixValue = prefixValue.PadRight(PrefixPattern.Length, ' ');
                    Text = prefixValue + Text.Substring(PrefixPattern.Length + 1);
                    SelectionStart = prePos.Length;
                    SelectionLength = 0;
                }
                return eatKey;
            }
            catch (Exception ex)
            {
            }
            return false;
        }
        //void ValidateBeforeSetText(string value)
        //{
        //    if (value.Length < Mask.Length)
        //      value=  value.PadLeft(Mask.Length, ' ');
        //}
        bool ProcessKeyAtSuffix(int position, int selectionLenght, Keys k)
        {
            try
            {
                if (k == Keys.Enter)
                {
                    ValidateInput();
                    if (ButtonCustom.Visible)
                        OnButtonCustomClick(EventArgs.Empty);
                    if (ButtonCustom2.Visible)
                        OnButtonCustom2Click(EventArgs.Empty);
                    return true;
                }
                int orginalPos = position;
                string suffixValue, prePos, sufPos;
                if (position == PrefixPattern.Length && k != Keys.Back)
                {
                    position = 0;
                }
                else
                    position = position - (PrefixPattern.Length + MiddlePattern.Length + 2);

                if (k == Keys.Left && position <= 0 && orginalPos > PrefixPattern.Length)
                {
                    SelectionStart = PrefixPattern.Length;
                    return true;
                }
                if (k == Keys.Right && position <= 0 && orginalPos > PrefixPattern.Length)
                {
                    SelectionStart = PrefixPattern.Length + MiddlePattern.Length + 2;
                    return true;
                }
                if (position < 0)
                    return false;

                if (k == Keys.Back && position == 0)
                {
                    SelectionStart = PrefixPattern.Length;
                    return true;
                }
                suffixValue = Text.Substring(PrefixPattern.Length + MiddlePattern.Length + 2);
                if (suffixValue.IndexOf('_') >= 0)
                    suffixValue = suffixValue.Replace('_', ' ');


                if (position <= suffixValue.Length)
                    prePos = suffixValue.Substring(0, position).Trim();
                else
                    prePos = "";

                if (position < suffixValue.Length)
                    sufPos = suffixValue.Substring(position + selectionLenght, PrefixPattern.Length - selectionLenght - position).Trim();
                else
                    sufPos = "";

                bool eatKey = ProcessKey(ref prePos, ref sufPos, k, true, position, selectionLenght);
                if (eatKey)
                {
                    suffixValue = prePos + sufPos;
                    suffixValue = suffixValue.PadRight(SuffixPattern.Length, ' ');
                    string prefixValue = Text.Substring(0, PrefixPattern.Length + MiddlePattern.Length + 2);
                    Text = prefixValue + suffixValue;
                    SelectionStart = PrefixPattern.Length + MiddlePattern.Length + 2 + prePos.Length;
                    SelectionLength = 0;
                }
                return eatKey;
            }
            catch (Exception ex)
            {
            }
            return false;
        }

        bool ProcessKey(ref string prePos, ref string sufPos, Keys k, bool atPre, int position, int selectionLenght)
        {
            bool eatIt = false;
            switch (k)
            {
                case Keys.Back:
                    if (position > 0)
                    {
                        if (prePos.Length > 0)
                            prePos = prePos.Substring(0, prePos.Length - 1);
                    }

                    eatIt = true;
                    break;
                case Keys.Delete:
                    if (position < PrefixPattern.Length && sufPos.Length > 0)
                        sufPos = sufPos.Substring(0, sufPos.Length - 1);
                    eatIt = true;
                    break;
                default:
                    KeysConverter kc = new KeysConverter();
                    if (k >= Keys.D0 && k <= Keys.D9)
                    {
                        int checkLength = atPre ? PrefixPattern.Length : SuffixPattern.Length;
                        if (sufPos.Length + prePos.Length < checkLength)
                        {
                            prePos += kc.ConvertToString(k);
                            eatIt = true;
                        }
                        else
                        {
                            if (position < checkLength)
                            {
                                prePos += kc.ConvertToString(k);
                                sufPos = sufPos.Substring(1);
                                eatIt = true;
                            }
                        }
                    }
                    break;
            }
            return eatIt;
        }


        protected override void OnLeave(EventArgs e)
        {
            ValidateInput();
            base.OnLeave(e);

        }

        public void ValidateInput()
        {
            try
            {
                string prefix = "";
                string suffix = "";
                if (Text.Length > PrefixPattern.Length + MiddlePattern.Length + 2)
                    prefix = Text.Substring(0, PrefixPattern.Length);
                if (Text.Length > PrefixPattern.Length + MiddlePattern.Length + 2)
                    suffix = Text.Substring(PrefixPattern.Length + MiddlePattern.Length + 2);
                int value = -1;
                prefix = prefix.Replace('_', ' ');
                suffix = suffix.Replace('_', ' ');

                if (int.TryParse(prefix, out value))
                {
                    if (suffix.Trim() == "")
                        suffix = DateTime.Now.Year.ToString();
                    else
                    {
                        if (suffix.Trim().Length < SuffixPattern.Length)
                        {
                            value = int.Parse(suffix);
                            string now = DateTime.Now.Year.ToString();
                            if (now.StartsWith(value.ToString()))
                                suffix = now;
                            else
                                if (now.EndsWith(value.ToString()))
                                    suffix = now;
                                else
                                {

                                    suffix = now.Substring(0, now.Length - value.ToString().Length) + value.ToString();

                                }
                        }

                    }
                }
                prefix = prefix.Trim().PadLeft(PrefixPattern.Length, ' ');
                suffix = suffix.Trim().PadRight(SuffixPattern.Length, ' ');
                Text = prefix + "/" + MiddlePattern + "/" + suffix;
            }
            catch (Exception ex)
            {

            }
        }
        [Browsable(false)]
        public string PrefixValueString
        {
            get
            {

                ValidateInput();
                try
                {
                    string prefix = "";

                    if (Text.Length > PrefixPattern.Length + MiddlePattern.Length + 2)
                        prefix = Text.Substring(0, PrefixPattern.Length);
                    prefix = prefix.Replace('_', ' ');
                    return prefix;
                }
                catch
                {
                }
                return "";
            }
        }
        [Browsable(false)]
        public int PrefixValue
        {
            get
            {
                int value = -1;
                int.TryParse(PrefixValueString, out value);
                return value;
            }
        }
        [Browsable(false)]
        public string SuffixValueString
        {
            get
            {
                try
                {
                    ValidateInput();
                    string suffix = "";
                    if (Text.Length > PrefixPattern.Length + MiddlePattern.Length + 2)
                        suffix = Text.Substring(PrefixPattern.Length + MiddlePattern.Length + 2);

                    suffix = suffix.Replace('_', ' ');

                    return suffix;
                }
                catch (Exception ex)
                {
                }
                return "";

            }
        }
        [Browsable(false)]
        public int SuffixValue
        {
            get
            {

                int value = -1;


                int.TryParse(SuffixValueString, out value);
                return value;
            }
        }



        #region ISupportInitialize Members
        bool isInit = false;
        public void BeginInit()
        {
            isInit = true;
        }

        public void EndInit()
        {
            isInit = false;
            PatternChange("", "");
        }

        #endregion
    }
}
